package cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.util;

import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.dto.VerifySealRespDTO;
import cn.maihe.elg.operation.utils.Base64Util;
import cn.maihe.elg.operation.utils.ElgLogger;
import cn.maihe.elg.operation.utils.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kinsec.KTConvert;
import com.kinsec.KTSignature;
import com.kinsec.SignatureInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author Alan
 * @Date 2024/12/12
 */
@Slf4j
public class KtOfdCloudSignatureUtil {

    private KTSignature ofdKTSignature;

    public KtOfdCloudSignatureUtil(KTSignature ofdKTSignature) {
        this.ofdKTSignature = ofdKTSignature;
        Assert.notNull(ofdKTSignature, () -> "ofdKTSignature不能为空");
    }

    public static class MySignatureInfo {
        ArrayList<SignatureInfo> signatureInfos = new ArrayList<>();

        public static MySignatureInfo init() {
            return new MySignatureInfo();
        }

        public MySignatureInfo add(String token, Integer page, Float x, Float y) {
            signatureInfos.add(new SignatureInfo(page, token, x, y));
            return this;
        }

        public ArrayList<SignatureInfo> toSignatureInfos() {
            return signatureInfos;
        }

    }

    /**
     * ofd云签 ofd签章
     *
     * @param sourceOfdPath
     * @param targetStampedOfdPath
     * @param appId
     * @param secret
     * @param signatureInfos
     * @return
     */
    public Path ofdStamps(Path sourceOfdPath, Path targetStampedOfdPath, String appId, String secret, ArrayList<SignatureInfo> signatureInfos) {
        try {
//            boolean stampFlag =
            this.ofdKTSignature.kt_ofdStamps(sourceOfdPath.normalize().toString(), appId, secret, signatureInfos, Files.newOutputStream(targetStampedOfdPath));
//            if (!stampFlag) {
//                throw new RuntimeException("ofd云签章失败");
//            }
//            if (Files.notExists(targetStampedOfdPath) || Files.size(targetStampedOfdPath) == 0) {
//                throw new RuntimeException("ofd签章后文件不存在或大小为0");
//            }
        } catch (Exception e) {
            throw new RuntimeException("ofd签章异常:" + e.getMessage(), e);
        }
        return targetStampedOfdPath;
    }

    /**
     * 文档ID自定义签章方法
     * @param sourceOfdPath
     * @param targetStampedOfdPath
     * @param docId 自定义文档ID
     * @param appId
     * @param secret
     * @param signatureInfos
     * @return
     */
    public Path ofdStamps(Path sourceOfdPath, Path targetStampedOfdPath, String docId, String appId, String secret, ArrayList<SignatureInfo> signatureInfos) {
        try {
//            boolean stampFlag =
            this.ofdKTSignature.kt_ofdStamps(sourceOfdPath.normalize().toString(), docId ,appId, secret, signatureInfos, Files.newOutputStream(targetStampedOfdPath));
//            if (!stampFlag) {
//                throw new RuntimeException("ofd云签章失败");
//            }
//            if (Files.notExists(targetStampedOfdPath) || Files.size(targetStampedOfdPath) == 0) {
//                throw new RuntimeException("ofd签章后文件不存在或大小为0");
//            }
        } catch (Exception e) {
            throw new RuntimeException("ofd签章异常:" + e.getMessage(), e);
        }
        return targetStampedOfdPath;
    }

    /**
     * ofd云签 pdf签章
     *
     * @param acceptOrderNo
     * @param sourceOfdPath
     * @param targetStampedOfdPath
     * @param appId
     * @param secret
     * @param signatureInfos
     * @return
     */
    public Path pdfStamps(String acceptOrderNo, Path sourceOfdPath, Path targetStampedOfdPath, String appId, String secret, ArrayList<SignatureInfo> signatureInfos) {
        try {
            ElgLogger.info(log, l -> l.info("acceptOrderNo={} << kt_pdfStamps请求:待签文件->{},已签文件->{},appId->{}", acceptOrderNo, sourceOfdPath.getFileName(), targetStampedOfdPath.getFileName(), appId));
            String jsonStr = this.ofdKTSignature.kt_pdfStamps(sourceOfdPath.normalize().toString(), appId, secret, signatureInfos);
            if (StringUtil.isNotEmpty(jsonStr)) {
                JSONObject jsonObject = JSON.parseObject(jsonStr);
                if (jsonObject.getIntValue("code") != 0) {
                    ElgLogger.info(log, l -> l.info("acceptOrderNo={} << kt_pdfStamps响应异常:{}", acceptOrderNo, jsonStr));
                    throw new RuntimeException("kt_pdfStamps签章响应异常,异常信息:" + jsonObject.getString("msg"));
                }
                JSONObject dataObject = jsonObject.getJSONObject("data");
                if (dataObject != null) {
                    String pdfBase64 = dataObject.getString("pdf");
                    if (StringUtil.isNotEmpty(pdfBase64)) {
                        Files.write(targetStampedOfdPath, Base64Util.mimeDecoder(pdfBase64));
                    } else {
                        throw new RuntimeException("kt_pdfStamps签章响应异常，返回值pdf为空");
                    }
                } else {
                    throw new RuntimeException("kt_pdfStamps签章响应异常，返回值data为空");
                }
            } else {
                throw new RuntimeException("kt_pdfStamps签章响应异常，返回值为空");
            }
        } catch (Exception e) {
            throw new RuntimeException("kt_pdfStamps签章异常:" + e.getMessage(), e);
        }
        return targetStampedOfdPath;
    }

    public List<VerifySealRespDTO> ofdVerifySeal(String acceptOrderNo, Path sourceOfdPath) {
        List<VerifySealRespDTO> verifySealRespDTOS = new ArrayList<>();
        try {
            ElgLogger.info(log, l -> l.info("acceptOrderNo={} << kt_verifyseal请求:验签文件->{}", acceptOrderNo, sourceOfdPath.getFileName()));
            String jsonStr = this.ofdKTSignature.kt_verifyseal(sourceOfdPath.normalize().toString(), 0, 0);
            ElgLogger.info(log, l -> l.info("acceptOrderNo={} << kt_verifyseal响应:{}", acceptOrderNo, jsonStr));
            if (StringUtil.isNotEmpty(jsonStr)) {
                JSONObject jsonObject = JSON.parseObject(jsonStr);
                if (jsonObject.getIntValue("code") != 0) {
                    throw new RuntimeException("kt_verifyseal验签响应异常,异常信息:" + jsonObject.getString("msg"));
                }
                if (jsonObject.getString("data") != null) {
                    verifySealRespDTOS = JSONObject.parseArray(jsonObject.getString("data"),VerifySealRespDTO.class);
                } else {
                    throw new RuntimeException("kt_verifyseal验签响应异常，返回值data为空");
                }
            } else {
                throw new RuntimeException("kt_pdfStamps验签响应异常，返回值为空");
            }
        } catch (Exception e) {
            throw new RuntimeException("kt_pdfStamps验签异常:" + e.getMessage(), e);
        }
        return verifySealRespDTOS;
    }

    public static void main(String[] args) {
//        KTSignature ktSignature = new KTSignature("58.22.60.120:18880");
        KTConvert ktConvert = new KTConvert("58.22.60.120:18880");
        KTSignature ktSignature = new KTSignature("58.22.60.120:18880");
        KtOfdCloudSignatureUtil ktOfdCloudSignatureUtil = new KtOfdCloudSignatureUtil(ktSignature);
        KtOfdCloudConvertUtil ofdCloudConvertUtil = new KtOfdCloudConvertUtil(ktConvert);
        Path pdf = Paths.get("d://abc.pdf");
        Path ofd = Paths.get("d://abc.ofd");
        ofdCloudConvertUtil.office2OfdWithMetas(pdf,ofd,null);
//        this.cloudSign = ktConfig.getCloudSign();
//        Assert.notNull(cloudSign, () -> "凯特云签服务cn.maihe.elg.kt.cloud-sign未配置");
//        ofdCloudSignatureUtil = new KtOfdCloudSignatureUtil(new KTSignature(cloudSign.getOfdServer()));
//        KtOfdCloudConvertUtil ofdCloudConvertUtil = new KtOfdCloudConvertUtil(new KTConvert(cloudSign.getOfdServer()));
//        office2OfdWithMetas

        Path ofdSigned = ofd.resolveSibling("abcSigned.ofd");
        Path pdfSigned = ofd.resolveSibling("abcSigned.pdf");

        String appId = "2AB718D2B13F4A6F8FF75086F44063D4";
        String secret = "8137F2FA2EE04B41AC0CD696CBAB5ECD";

        String token = "FNTMvg59UoGL3owEb5BpLDRmgYHzB1+Dj4Mu06gBWp1UuTBB7QZ9zk46wRHdMLG5v98UZX9yapNOkleqVz7V5nxi7d15r9Ao1Mv5v0ENSYCgE0j9al4pUfqRxmxiNVMh/1fZMz6VxA6Qad6KjCnBPRjOagJ+GeyZ/dJx+g5A3ffn3rkYJ/S7eFOV+IxslTlW5Kk9IlfOy3wY97zQeBhnKTGuGbKhhayOzSEaSt9vjrmKHeVUQgiV8MBZLegDI9O6VEwVIirhS7DeV80A6tNKc3GnF9Fbz3ywgRAMR38ps2s=";
        String legalToken = "FNTMvg59UoGL3owEb5BpLDRmgYHzB1+Dj4Mu06gBWp1UuTBB7QZ9zk46wRHdMLG5wD7sR21HIrByP/PNGv2u9sagYADYR+9z0c/3ElUUyij5BgZelCithebVWicFfnIrY+3fgAgQGXDcm/tFen8OrnGHiZpZgB9ccqsRtn7mRs08vKwi6Uibn0K9mvrmxIY1nm6Bld/KtzksnuR+CNNzwptXXN/JpcRHM0aiSixR+Bs7a0hx91jqbyuxMtgzB8QNzJzMe0q75OOzvhV0GspwzpUlhatDIaEFmZJiGk+GG2w=";

        ArrayList<SignatureInfo> signtureinfos = new MySignatureInfo()
                .add(token, 1, 68f, 197f)
                .add(legalToken, 1, 115f, 213f).toSignatureInfos();

//        KtOfdCloudConvertUtil ofdCloudConvertUtil = new KtOfdCloudConvertUtil(new KTConvert("58.22.60.120:18880"));
        ofdCloudConvertUtil.office2Ofd(pdf, ofd);

//        util.ofdStamps(ofd, ofdSigned, appId, secret, signtureinfos);

        ArrayList<SignatureInfo> signatureInfos = new ArrayList<>();

        SignatureInfo signatureInfo = new SignatureInfo(0, token, 0, 0);
        SignatureInfo signatureInfo2 = new SignatureInfo(0, token, "2", 50, 50);
        signatureInfos.add(signatureInfo);
        signatureInfos.add(signatureInfo2);

//        Path path = ktOfdCloudSignatureUtil.pdfStamps("test001", pdf, pdfSigned, appId, secret, signatureInfos);
//        try {
//            Files.deleteIfExists(pdf);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        util.ofdVerifySeal("test001", ofdSigned);
//        System.out.println(path);

        ktOfdCloudSignatureUtil.ofdVerifySeal("test001", ofdSigned);
    }

}
